#!/usr/bin/perl
use Encode;


#reading source csv file name from @ARGV[0]

$inputfile = @ARGV[0];
$separatoroption = @ARGV[1];



# setting output filename
$outputfile = $inputfile;
$outputfile =~ s/.csv/.vcf/i;
if ($outputfile eq $inputfile)
    {
    $outputfile=$outputfile.".vcf";
    }

#incremeting value
$i = 66400000000;

#current date calculation and transform
($cur_sec,$cur_min,$cur_hour,$cur_mday,$cur_mon,$cur_year,$cur_wday,$cur_yday,$cur_isdst) = localtime(time);
$cur_year = sprintf("%02d", $cur_year % 100);

$cur_mon=$cur_mon+1;
if ($cur_mday<10) {$cur_mday="0".$cur_mday};
if ($cur_mon<10) {$cur_mon="0".$cur_mon};
if ($cur_hour<10) {$cur_hour="0".$cur_hour};
if ($cur_min<10) {$cur_min="0".$cur_min};
if ($cur_sec<10) {$cur_hour="0".$cur_sec};

$cur_year="20".$cur_year;
$cur_date=$cur_mday.".".$cur_mon.".".$cur_year;
              
$vcarddate="REV:".$cur_year."-".$cur_mon."-".$cur_mday."T".$cur_hour.":".$cur_min.":".$cur_sec."Z";

if ($inputfile ne "" and $separatoroption ne "")
    {
    if ($separatoroption eq "-separator=comma")
	{
	$separator = ",";
	}

    if ($separatoroption eq "-separator=semicolon")
	{
	$separator = ";";
	}


    print "Opening file: $inputfile\n";
#    open FH, $inputfile or die "Cannot open $inputfile for reading!\n";
    open (FH, "<:raw:encoding(UTF-16)", $inputfile) or die "Cannot open $inputfile for reading!\n";
    open (FHOUT, ">$outputfile" ) or die "Cannot write $outputfile for reading!\n";

# setting conversion from unicode encoding to utf-8
    @inputfilelines=<FH>;
	foreach (@inputfilelines)
	{

# debug
#	print $_;

	@contactsarray = split($separator,$_);

# importing name, company, e-mail
	$vcardstring = "BEGIN:VCARD\nVERSION:3.0\nUID:pas-id-519B0".$i."\nN:".@contactsarray[1]." ".@contactsarray[3]."\nORG:".@contactsarray[6]."EMAIL;TYPE=INTERNET:".@contactsarray[15]."\n";

# importing various phone numbers
	if (@contactsarray[12] ne "")
	    {
	    $vcardstring=$vcardstring."TEL;TYPE=CELL:".@contactsarray[13]."\n";
	    }
	if (@contactsarray[13] ne "")
	    {
	    $vcardstring=$vcardstring."TEL;TYPE=HOME:".@contactsarray[14]."\n";
	    }
	if (@contactsarray[27] ne "")
	    {
	    $vcardstring=$vcardstring."TEL;TYPE=WORK:".@contactsarray[27]."\n";
	    }
	if (@contactsarray[28] ne "")
	    {
	    $vcardstring=$vcardstring."TEL;TYPE=FAX:".@contactsarray[28]."\n";
	    }

# closing record
    $vcardstring = $vcardstring.$vcarddate."\nEND:VCARD\n\n";



# removing double quotes
	$vcardstring =~ s/\"//g;

# incrementing
	$i=$i+1;

# writing outputfile
	print FHOUT $vcardstring;
	
	}

    close FH;
    close FHOUT;
    }
else
    {
    print "Syntax: nokia_csv_vcard somefile.txt -separator=comma\n or -separator=semicolon.\n";
    }